package com.qihetimes.earthangel.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qihetimes.earthangel.common.IntegralChangeType;
import com.qihetimes.earthangel.common.MessageType;
import com.qihetimes.earthangel.model.ConversationMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 小程序订阅消息服务
 *
 * @author ：f4cklangzi@gmail.com
 * @date ：Created At 2022/1/16
 */
@Slf4j
@Service
public class WxAppMessageService {
    
    /**
     * 好友添加
     */
    private static final String FRIEND_ADD = "pJYzWj77glqBtdUJfftsc9-LbJOoRMfIKuZy2sQ7oU8";
    
    /**
     * 等级变动
     */
    private static final String LEVEL_CHANGE = "QDbybd5AGeCJFBSO1SMQ2ivZ6R7NBSfiSeOmRJPudVQ";
    
    /**
     * 积分变动
     */
    private static final String INTEGRAL_CHANGE = "Uiiklc7fm2A3hz_kcc5OxTOTz180DdZIIBjYryG8vtg";
    
    @Resource
    private WxMaService wxMaService;
    
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    
    public void sendPush(String openid, ConversationMessage message) {
        taskExecutor.execute(() -> asyncSend(openid, message));
    }
    
    @SneakyThrows
    private void asyncSend(String openid, ConversationMessage message) {
        WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
        subscribeMessage.setToUser(openid);
        List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
        String date = LocalDateTimeUtil.format(message.getCreatedAt(), DatePattern.NORM_DATETIME_FORMATTER);
        MessageType messageType = MessageType.valueOf(message.getMessageType());
        switch (messageType) {
            case FRIEND_ADD:
                String userName = JSONUtil.parseObj(message.getContent()).getStr("nickName");
                dataList.add(new WxMaSubscribeMessage.MsgData("thing1", userName));
                dataList.add(new WxMaSubscribeMessage.MsgData("time2", date));
                subscribeMessage.setTemplateId(FRIEND_ADD);
                subscribeMessage.setData(dataList);
                wxMaService.getSubscribeService().sendSubscribeMsg(subscribeMessage);
                break;
            case INTEGRAL_CHANGE:
                JSONObject content = JSONUtil.parseObj(message.getContent());
                Integer newIntegral = content.getInt("newIntegral");
                Integer oldIntegral = content.getInt("oldIntegral");
                Integer oldLevel = content.getInt("oldLevel");
                Integer newLevel = content.getInt("newLevel");
                IntegralChangeType changeType = IntegralChangeType.valueOf(content.getStr("changeType"));
                int changeCount = newIntegral - oldIntegral;
                dataList.add(new WxMaSubscribeMessage.MsgData("amount1", String.valueOf(changeCount)));
                dataList.add(new WxMaSubscribeMessage.MsgData("time2", date));
                dataList.add(new WxMaSubscribeMessage.MsgData("thing3", changeType.getMark()));
                subscribeMessage.setTemplateId(INTEGRAL_CHANGE);
                subscribeMessage.setData(dataList);
                wxMaService.getSubscribeService().sendSubscribeMsg(subscribeMessage);
                if (!newLevel.equals(oldLevel)) {
                    dataList = new ArrayList<>();
                    dataList.add(new WxMaSubscribeMessage.MsgData("thing4", String.valueOf(oldLevel)));
                    dataList.add(new WxMaSubscribeMessage.MsgData("thing5", String.valueOf(newLevel)));
                    subscribeMessage = BeanUtil.toBean(subscribeMessage, WxMaSubscribeMessage.class);
                    subscribeMessage.setTemplateId(LEVEL_CHANGE);
                    subscribeMessage.setData(dataList);
                    wxMaService.getSubscribeService().sendSubscribeMsg(subscribeMessage);
                }
                break;
            default:
        }
    }
}
